#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/9/6 11:11
# @File           : __init__
# @IDE            : PyCharm
# @desc           : 描述

from datetime import datetime
from typing import List
from fastapi import APIRouter, Depends
from utils.response import SuccessResponse
from . import schemas, crud, params
from core.dependencies import IdList
from core.exception import CustomException
from apps.base.auth.validate import AllUserAuth, Auth
from apps.check.task.crud import QARTaskDal
from apps.check.task.schemas import QARTaskSimpleOut


app = APIRouter()


@app.get("/qar", summary="获取QAR表单")
async def get_qar(
        p: params.QARParams = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    datas, count = await crud.QARDal(auth.db).get_datas(
        **p.dict(),
        v_schema=schemas.QARSimpleOut,
        v_return_count=True
    )
    return SuccessResponse(datas, count=count)


@app.post("/qar/{method}", summary="创建QAR表单")
async def create_qar(
        method: str,
        datas: List[QARTaskSimpleOut],
        auth: Auth = Depends(AllUserAuth())
):

    if method == "single":
        fail = 0
        for data in datas:
            schema = schemas.QARIn(**data.model_dump())
            schema.create_user = auth.user.user_str
            try:
                await crud.QARDal(auth.db).create_data(schema)
            except CustomException:
                fail += 1
                raise
            except Exception:
                raise
            else:
                await QARTaskDal(auth.db).delete_datas([data.id])
        return SuccessResponse(f"共 {len(datas)} 项，创建 {len(datas) - fail} 项， 失败 {fail} 项")

    elif method == "merge":
        schema = schemas.QARIn(**datas[0].model_dump())
        schema.create_user = auth.user.user_str
        material_nos, purchase_orders = [schema.material_no], [schema.purchase_order]
        for tmp in datas[1:]:
            if tmp.part_no != schema.part_no:
                raise CustomException("不同件号无法合并")
            material_nos.append(tmp.material_no)
            purchase_orders.append(tmp.purchase_order)
        
        schema.material_no = ";".join(material_nos)
        schema.purchase_order = ";".join(purchase_orders)
        res = await crud.QARDal(auth.db).create_data(schema)

        await QARTaskDal(auth.db).delete_datas([data.id for data in datas])
        
        return SuccessResponse(f"共 {len(datas)} 条记录合并，创建 QAR 为：{res['qar_no']}")


@app.put("/qar/{data_id}", summary="更新QAR表单")
async def put_qar(
        data_id: int,
        data: schemas.QARUpdate,
        auth: Auth = Depends(AllUserAuth())

):
    obj = await crud.QARDal(auth.db).get_data(data_id=data_id)
    if obj.status != "检验中":
        raise CustomException("当前状态QAR不允许修改")
    return SuccessResponse(await crud.QARDal(auth.db).put_data(data_id, data=data))


@app.put("/qar/{data_id}/stamp", summary="QAR表单计划或检验员刷卡")
async def put_qar_stamp(
        data_id: int,
        data: schemas.QARStampType,
        auth: Auth = Depends(AllUserAuth())
):
    obj = await crud.QARDal(auth.db).get_data(data_id=data_id)
    if data.type == "inspected_by":
        obj.inspected_by = auth.user.user_str_time
    elif data.type == "prepared_by":
        obj.prepared_by = auth.user.user_str_time
    await crud.QARDal(auth.db).flush(obj)
    return SuccessResponse("更新成功")


@app.put("/qar/{data_id}/status", summary="更新QAR表单状态")
async def put_qar_status(
        data_id: int,
        data: schemas.QARUpdateStatus,
        auth: Auth = Depends(AllUserAuth())

):
    obj = await crud.QARDal(auth.db).get_data(data_id=data_id)
    if obj.status == "归档":
        raise CustomException("归档QAR不允许更新状态")
    if data.status and data.status == '作废':
        obj.status = '作废'
    else:
        if obj.status == "已发布":
            obj.status = '检验中'

        elif obj.status == '检验中':
            obj.status = '委托中'

        elif obj.status == '委托中':
            await crud.QARDal(auth.db).check_previous(qar_no=obj.qar_no)
            obj.status = '检验完成'

        elif obj.status == '检验完成':
            obj.status = '归档'

    await crud.QARDal(auth.db).flush(obj)
    return SuccessResponse("更新成功")


@app.get("/qar/{data_id}", summary="获取QAR表单详情")
async def get_qar_detail(
        data_id: int,
        auth: Auth = Depends(AllUserAuth())
):
    return SuccessResponse(await crud.QARDal(auth.db).get_data_detail(data_id=data_id))


@app.delete("/qar", summary="批量删除QAR表单", description="软删除")
async def delete_qar(ids: IdList = Depends(), auth: Auth = Depends(AllUserAuth())):
    await crud.QARDal(auth.db).delete_datas(ids=ids.ids, v_soft=True, delete_user=auth.user.user_str)
    return SuccessResponse("删除成功")
